import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Block} from '@tarojs/components'
import {AtIcon} from 'taro-ui';
import {
  GET_NEWS_GY_ID,
  LIMIT_FROM_SELLER_SINCE,
  NEWS_PAGE, CONTENT_QR, CONTENT_QRWX, TARO_ENV, UPDATE_USER_SHARE_DATE, SCAN_BIND_SELLER, H5_VIDEO
} from '../../constants/api'
import {user} from '../../utils/user.service';
import {platform} from '../../utils/platform-settting.service';
import {http} from '../../utils/http';
import {NewsInfo, NewsRecommendItem} from '../../utils/server.interface';
import {getPoster} from "../../utils/poster.service";
import OtherBar from '../components/detail-bar/other-bar';
import {GetRequest, getTempSellerId, vcmonitor, setTempSellerId} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Category from "../../pages/index/template/regionalCategory/component/category";
import {getContent} from "../../utils/handlerPublicCode";
import './detail.scss';

interface NewsType {
  news: NewsInfo
  list: NewsRecommendItem[]
  date: string
}

let iframe = ''
if (process.env.TARO_ENV === 'h5') {
  iframe = document.createElement("iframe");
}

export default class Detail extends Component {
  state: {
    uuid: string
    list: NewsRecommendItem[]
    news: NewsInfo
    newsDate: any
    isUser: boolean
    playStatus: boolean
    modalShow: boolean
    qrImg: any
    tempSellerId?: any
    wxModalShow: boolean
    wxQrImg: any
  } = {
    isUser: true,
    uuid: '',
    list: [],
    newsDate: '',
    playStatus: false,
    news: {
      title: '', uuid: '', content: '', author: '', view_count: 0
    },
    modalShow: false,
    qrImg: '',
    tempSellerId: '',
    wxModalShow: false,
    wxQrImg: ''
  }

  async UNSAFE_componentWillMount() {
    if (!process.env.IS_SHOW_LIVING_CODE) {
      return false
    }
    const res = await http.HGet(CONTENT_QR);
    const wxres = await http.HGet(CONTENT_QRWX);
    this.setState({
      qrImg: res.data, wxQrImg: wxres.data
    })
  }

  shareParams = ''

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    const news = this.state.news
    if (news.share_img) {
      return {
        title: news.title,
        path: "/common/news/detail?uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
        imageUrl: news.share_img
      }
    }
    return {
      title: news.title,
      path: "/common/news/detail?uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  onShareTimeline() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    const news = this.state.news
    if (news.share_img) {
      return {
        title: news.title,
        query: "uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
        imageUrl: news.share_img
      }
    }
    return {
      title: news.title,
      query: "uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  async componentDidShow() {
    vcmonitor(this)
    let isUser = true
    const isLogin = await user.checkLogin();
    if (isLogin) {
      const userIdentity = await user.getUserData()
      if (userIdentity && userIdentity.isSeller) {
        isUser = false
      }
    }
    this.setState({isUser})
    let uuid = ''
    let tempSellerId = getTempSellerId(this)
    this.setState({tempSellerId})
    let bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    let tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    const param = Taro.getCurrentInstance().router.params.scene as string | undefined;
    if (param && /^\d+_\d+_\d+$/.test(param)) {
      platform.scene = 0;
      const paramArr = param.split('_'); // [ itemId, sellerId, bindSellerId, sid ] 长度不固定
      if (!paramArr[0] || !paramArr[1] || !paramArr[2]) {
        Taro.showToast({
          title: '无效的参数',
          icon: 'none'
        });
        Taro.switchTab({url: '/pages/index/index'})
        return false;
      }
      if (paramArr[2]) {
        tempSellerId = tempSellerIds = bindSellerIds = paramArr[2]
        setTempSellerId(tempSellerId)
        this.setState({tempSellerId})
      }
      user.bindSellerId = paramArr[2]
      Taro.setStorage({
        key: 'bindSellerId',
        data: user.bindSellerId
      })
      Taro.setStorage({
        key: 'bindSellerId',
        data: user.bindSellerId,
        success: res => {
          if (user.bindSellerId) {
            Taro.login({
              success(res) {
                if (res.code) {
                  const integralForm = {
                    sellerId: user.bindSellerId,
                    code: res.code
                  }
                  http.post(LIMIT_FROM_SELLER_SINCE, integralForm);
                } else {
                  console.log('登录失败！' + res.errMsg)
                }
              }
            })

          }
        }
      })
      const ret = await http.get<{ uuid: string }>(GET_NEWS_GY_ID, {id: paramArr[0]})
      uuid = ret ? ret.uuid : ''
    } else {
      uuid = Taro.getCurrentInstance().router.params.uuid || ''
    }
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, { temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds });
    }
    const result = await http.get<NewsType>(NEWS_PAGE + '/' + uuid, {})
    if (result) {
      const setting = await platform.getSetting()
      if (setting && setting.platformName) {
        Taro.setNavigationBarTitle({
          title: setting.platformName || ''
        })
      }
      if (TARO_ENV === 'h5') {
        const h5Parser = document.getElementById('h5Parser')
        h5Parser.innerHTML = result.news.content
      }
      this.setState({news: result.news, newsDate: result.date, list: result.list})
    }
    this.shareParams = await user.getSellerParams(tempSellerId)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      let mpkey = ''
      const uInfo = Taro.getStorageSync('user') || ''
      if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
        mpkey = uInfo.mpkey
      }
      const shareData = {
        title: platform.info.platformName,
        desc: result.news.title,
        link: window.location.origin + "/common/news/detail?uuid=" + uuid  + '&mpkey=' + mpkey + '&' + this.shareParams,
        imgUrl: result.news.share_img
      }
      h5Wx.share(shareData)
    }
    this.setState({uuid})
  }

  async onGetPoster() {
    Taro.showLoading({title: '获取海报中...'});
    const poster = await getPoster('news', this.state.uuid || '', '', this.state.tempSellerId)
    Taro.hideLoading();
    if (poster) {
      Taro.navigateTo({url: '/distributor/poster/poster?url=' + poster.url})
    } else {
      Taro.showToast({title: '获取海报失败！', icon: 'none'})
    }
  }

  play() {
    let txv = ''
    try {
      txv = Taro.requirePlugin("tencentvideo")
    } catch (e) {
      txv = ''
    }
    const TxvContext = txv;
    const txvContext = TxvContext && TxvContext.getTxvContext('myVideo')
    if (this.state.playStatus) {
      txvContext && txvContext.pause();
    } else {
      txvContext && txvContext.play();
    }
    this.setState({playStatus: !this.state.playStatus})
  }

  playState(s) {
    this.setState({playStatus: s})
  }

  async onOpenModel() {
    this.setState({modalShow: true})
  }

  async handleCancel() {
    this.setState({modalShow: false})
  }

  handleClose() {
    this.setState({modalShow: false})
  }

  async onWXOpenModel() {
    this.setState({wxModalShow: true})
  }

  async wxhandleCancel() {
    this.setState({wxModalShow: false})
  }

  render() {
    const {
      news, list, newsDate, playStatus, modalShow,
      qrImg,
      isUser,
      wxModalShow,
      wxQrImg
    } = this.state;
    return (
      <View className='news-root'>
        <GzhAuth />
        <View className='header'>
          <View className='title'>{news.title}</View>
          <View className='description'>
            <Text className='author'>{news.author}</Text>
            <Text className='date'>{newsDate}</Text>
          </View>
        </View>
        {news && news.qq_video_id && process.env.TARO_ENV !== 'tt' && <View className='detail-header-box'>
          {process.env.TARO_ENV != 'h5' ? <Block>
            <txv-video
              width='100vw'
              height='100%'
              controls={false}
              loop
              className='video'
              vid={news.qq_video_id}
              playerid='myVideo'
              object-fit='contain'
              isNeedMutex
              isHiddenStop
              showCenterPlayBtn={false}
              onPlay={this.playState.bind(this, true)}
              onPause={this.playState.bind(this, false)}
            />
            <View className='btn-box'>
              <View className='left'>
                {!playStatus && <AtIcon value='play' size='30' color='#FFF' onClick={this.play.bind(this)} />}
                {playStatus && <AtIcon value='pause' size='30' color='#FFF' onClick={this.play.bind(this)} />}
              </View>
            </View>
          </Block> : <Block>
            <iframe src={H5_VIDEO + news.qq_video_id} style={`height:${window.innerWidth * 0.75 + 'px'};width: 100%;`} allowFullScreen='true' frameBorder='0' />
          </Block> }
        </View>
        }
        <View className='content'>
          {process.env.TARO_ENV === 'h5' && <View id='h5Parser' />}
          {process.env.TARO_ENV === 'weapp' && <parser html={news.content || ''} />}
          {process.env.TARO_ENV === 'tt' && <rich-text preview selectable nodes={getContent(news.content)} />}
          <View className='visited'>阅读 {news.view_count}</View>
        </View>
        {list && list.length > 0 && <View className='other'>
          <View className='title no-p-b'>相关产品</View>
          <View className='content no-p-b no-p-t no-p-r-l'>
            <Category itemsNoPaddingLR='true' data={list} isUser={isUser} />
          </View>
        </View>}
        {news.share_img && <OtherBar isShowShareButton onGetPoster={async () => {
          await this.onGetPoster()
        }} showLoading={false} onGotoHome={() => {
          Taro.switchTab({url: '/pages/index/index'})
        }} onContact={() => {
          Taro.navigateTo({url: `/distributor/contact/contact`})
        }}
          onOpenModel={this.onOpenModel.bind(this)} modalShow={modalShow}
          handleCancel={this.handleCancel.bind(this)} qrImg={qrImg}
          onWXOpenModel={this.onWXOpenModel.bind(this)} wxModalShow={wxModalShow}
          wxhandleCancel={this.wxhandleCancel.bind(this)} wxQrImg={wxQrImg}
        />}
      </View>
    );
  }
}
